<template>
  <div class="Progress-neg-container">
    <div class="title">Top 5 areas for improvement</div>

    <!-- 优先显示父组件触发的加载状态（数据更新时） -->
    <div v-if="isParentLoading" class="loading-state">
      <div class="spinner"></div>
      <div class="loading-text">Loading new data...</div>
    </div>
    <!-- 初始加载状态（组件刚挂载时） -->
    <div v-else-if="isInitialLoading" class="loading-state">
      <div class="spinner"></div>
      <div class="loading-text">Loading initial data...</div>
    </div>
    <!-- 空状态：数据为空时显示 -->
    <div
      v-else-if="!improvements || improvements.length === 0"
      class="empty-state"
    >
      No improvement areas data available
    </div>
    <!-- 图表：数据加载完成后显示 -->
    <div class="chart-container" v-else>
      <PieChart :option="chartOption" :height="'1.4375rem'"></PieChart>
    </div>
  </div>
</template>

<script>
import { fontChart } from "@/utils/echartPxToRem";
import PieChart from "@components/common/PieChart.vue";

export default {
  components: {
    PieChart,
  },
  props: {
    improvements: {
      type: [Array, null],
      default: null,
    },
    // 接收父组件的加载状态（数据更新时触发）
    isParentLoading: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      isInitialLoading: true, // 仅用于初始加载的状态
      initialTimer: null, // 初始加载超时计时器
    };
  },
  computed: {
    processedData() {
      // 新增降序排序逻辑：按count字段从大到小排序后取前5条
      return this.improvements
        ? [...this.improvements]
            .sort((a, b) => Number(b.count) - Number(a.count)) // 降序排序
            .slice(0, 5)
        : [];
    },
    chartOption() {
      const data = this.processedData;
      const potentialData = data.map((item) => Math.round(item.count * 1.5));

      return {
        tooltip: {
          trigger: "item",
          axisPointer: { type: "shadow" },
          extraCssText:
            "border: none; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); padding: 8px 12px;",
          formatter: (params) => {
            const item = data[params.dataIndex];
            return `${item.phrase}<br/>${params.seriesName}: ${params.value}`;
          },
        },
        grid: {
          left: 270,
          right: "5%",
          top: "7%",
          bottom: "0%",
          containLabel: false,
        },
        xAxis: {
          type: "value",
          show: false,
        },
        yAxis: {
          type: "category",
          data: data.map((item, index) => `${index + 1}. ${item.phrase}`),
          inverse: true,
          axisLine: { show: false },
          axisTick: { show: false },
          axisLabel: {
            align: "left",
            margin: 270,
            verticalAlign: "middle",
            color: "#232323",
            fontSize: 12,
            overflow: "truncate",
            fontWeight: "400",
          },
          boundaryGap: [0.1, 0.1],
        },
        series: [
          {
            name: "Real rate",
            type: "bar",
            stack: "total",
            barWidth: 18,
            label: {
              show: true,
              position: "insideRight",
              formatter: (params) => params.value,
              color: "#fff",
              fontSize: 10,
              fontWeight: "bold",
              emphasis: {
                fontSize: 12,
              },
            },
            data: data.map((item) => item.count),
            itemStyle: {
              color: "#CE4049",
              borderColor: "#fff",
              borderWidth: 2,
              borderRadius: [6, 6, 6, 6],
            },
          },
        ],
      };
    },
  },
  watch: {
    // 监听父组件传来的新数据，关闭所有加载状态
    improvements(newVal) {
      if (newVal) {
        this.isInitialLoading = false;
        if (this.initialTimer) clearTimeout(this.initialTimer);
      }
    },
    // 监听父组件的加载状态，强制覆盖旧数据显示加载
    isParentLoading(newVal) {
      // 父组件开始请求时，即使有旧数据也显示加载
      if (newVal) {
        this.isInitialLoading = false; // 避免与初始加载冲突
      }
    },
  },
  mounted() {
    // 初始加载超时处理（防止父组件长时间无响应）
    this.initialTimer = setTimeout(() => {
      this.isInitialLoading = false;
    }, 15000);

    // 若初始已有数据，直接关闭初始加载状态
    if (this.improvements && this.improvements.length > 0) {
      this.isInitialLoading = false;
      clearTimeout(this.initialTimer);
    }
  },
  beforeDestroy() {
    if (this.initialTimer) clearTimeout(this.initialTimer);
  },
};
</script>

<style scoped lang="scss">
.Progress-neg-container {
  background: #fff;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  padding: 16px 24px;
  border-radius: 8px;
  border: 1px solid #cdcccc;

  .title {
    font-size: 0.125rem;
    color: #454545;
    font-weight: 600;
    // margin-bottom: 10px;
  }

  .empty-state {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 1.4375rem;
    color: #666;
    font-size: 14px;
    background-color: #f9f9f9;
    border-radius: 4px;
  }

  .loading-state {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 1.4375rem;
    gap: 12px;
    background-color: #f9f9f9;
    border-radius: 4px;

    .spinner {
      width: 24px;
      height: 24px;
      border: 3px solid rgba(206, 64, 73, 0.2);
      border-top-color: #ce4049;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }

    .loading-text {
      color: #999;
      font-size: 0.0972rem !important;
      font-family: "Inter Variable", sans-serif;
    }
  }
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>
